<template>
	<!-- 固定收藏列表：分离布局，添加 touch-action -->
	<view class="">
		<view class="navi-bar" v-if="!isAction">
			<view class="navi-left" @click="naviback">
				<uni-icons type="left" color="#fff"></uni-icons>
			</view>
			<view class="navi-info" v-if="!searchMode">新会话</view>
			<view class="navi-search" v-if="searchMode">
				<input class="search" type="search" auto-focus="true" @input="searchKeyword" :placeholder="placeholder" placeholder-style="color:#dedede;fontSize:24rpx" />
			</view>
			<view class="navi-right">
				<view class="" @click="handleSearchMode">
					<uni-icons :type="searchMode ? 'closeempty' : 'search'" color="#fff"></uni-icons>
				</view>
				<view>
					<uni-icons type="map" color="#fff"></uni-icons>
				</view>
			</view>
		</view>
		<contactToptool :isShow="isAction" :chat-item="currentPressItem" @close="isAction = false"></contactToptool>
		<view class="action">
			<view class="action-bar" :class="{ current: actionType === 'person' }" @click="action('person')">
				<uni-icons type="person" size="26"></uni-icons>
				<text>好友</text>
			</view>

			<view class="action-bar" :class="{ current: actionType === 'favorite' }" @click="action('favorite')">
				<uni-icons type="location" size="26"></uni-icons>
				<text>位置收藏</text>
			</view>

			<view class="action-bar" :class="{ current: actionType === 'group' }" @click="action('group')">
				<uni-icons type="staff" size="26"></uni-icons>
				<text>群聊天</text>
			</view>
		</view>
		<view class="selc-list" v-if="selcList.length">
			<view class="selc-item" v-for="(item, index) in selcList" :key="item.friendDetail.userId">
				<view class="avatar-box">
					<AvatarFallback v-if="!item.friendDetail.avatar" :name="item.remarkName"></AvatarFallback>
					<image class="avatar" :src="item.friendDetail.avatar" mode=""></image>
				</view>
				<text class="item-text">{{ item.remarkName }}</text>
			</view>
		</view>

		<!-- 独立滚动容器：避免全局滚动冲突 -->
		<view class="scroll-container" :style="{ marginTop: 260 + 'rpx' }">
			<view class="favorite" v-if="actionType === 'all' || actionType === 'favorite'">
				<view v-if="favoriteShow">
					<favorite-bar :favorites="computedFavorites" @toFavoriteChat="toFavoriteChat" @pressItem="handlePressItem"></favorite-bar>
				</view>
			</view>

			<view class="group" v-if="actionType === 'all' || actionType === 'group'">
				<view v-if="groupShow">
					<group-item :groups="computedGroup" @toGroupChat="toGroupChat" @pressItem="handlePressItem"></group-item>
				</view>
			</view>

			<view class="person" v-if="actionType === 'all' || actionType === 'person'">
				<view v-if="isLoading" class="loading">加载中...</view>
				<view v-if="!isLoading && contact.length === 0" class="empty">暂无联系人</view>
				<view
					v-if="personShow"
					v-for="(person, index) in contact"
					:key="person.friendDetail.userId"
					@click="select(person, index)"
					:class="{ 'selc-person': selectedIndexes.includes(index) || person.friendUserId === friendUserId }"
				>
					<person-item :person="person" @pressItem="handlePressItem"></person-item>
				</view>
			</view>
		</view>
		<uni-popup ref="popup"></uni-popup>
		<view class="btn" :class="{ 'btn-hidden': isBtnHidden }" @click="handleBtn">
			<uni-icons v-if="actionType === 'person'" type="personadd" color="#fff" size="30" @click="personadd"></uni-icons>
			<uni-icons v-if="actionType === 'group'" type="staff-filled" color="#fff" size="30"></uni-icons>
			<uni-icons v-if="actionType === 'favorite'" type="location" color="#fff" size="30"></uni-icons>
		</view>
	</view>
</template>

<script>
// 脚本部分无需修改，保持之前修正后的代码即可
import PersonItem from '@/components/person.vue';
import FavoriteBar from '../../components/favoriteBar.vue';
import AvatarFallback from '../../components/AvatarFallback.vue';
const friend = uniCloud.importObject('friend', { customUI: true });
const group = uniCloud.importObject('groupManager', { customUI: true });
import groupItem from '../../components/group-item.vue';
import PreloadManager from '../../utils/PreloadManager';
import setToTarget from '../../utils/setTarget';
import contactToptool from '../../components/contactToptool.vue';
export default {
	components: {
		PersonItem,
		FavoriteBar,
		AvatarFallback,
		groupItem,
		contactToptool
	},
	computed: {
		storeData() {
			return this.$store.state.msg;
		},
		computedFavorites() {
			return this.favorites.filter((item) => item.name.includes(this.keyword) || item.address.includes(this.keyword));
		},
		computedGroup() {
			return this.groups.filter((item) => item.groupName.includes(this.keyword) || item.signature.includes(this.keyword));
		}
	},

	data() {
		return {
			currentPage: 1,
			currentIndex: -1,
			pageSize: 20,
			contact: [],
			selectedIndexes: [],
			groups: [],
			favorites: [],
			isLoading: false,
			favoriteShow: true,
			groupShow: true,
			personShow: true,
			selcListHeight: 0,
			selcList: [],
			actionType: 'person',
			searchMode: false,
			isBtnHidden: false,
			placeholder: '搜索',
			keyword: '',
			type: '',
			groupId: '',
			isAction: false,
			currentPressItem: {},
			friendUserId: ''
		};
	},
	onLoad(res) {
		if (res?.groupId && res?.type) {
			this.groupId = res.groupId;
			this.type = res.type;
		}

		this.loadContacts();
		this.favorites = this.storeData?.user?.favorite || [];
		this.getGroups();
	},
	onReachBottom() {
		this.loadMoreContacts();
	},
	methods: {
		searchKeyword(e) {
			this.keyword = e.detail.value;
			console.log(this.keyword);
			if (this.actionType === 'person') {
				this.loadContacts(this.keyword);
			}
		},
		inputValue(e) {
			console.log(e);
		},
		handleSearchMode() {
			this.searchMode = !this.searchMode;
			if (!this.searchMode) this.keyword = '';
			if (this.searchMode) {
				switch (this.actionType) {
					case 'person':
						this.placeholder = '搜索联系人/手机号';
						break;
					case 'group':
						this.placeholder = '搜索群名/群介绍关键字';
						break;
					case 'favorite':
						this.placeholder = '搜索收藏名称/地址关键字';
						break;
					default:
						this.placeholder = '搜索';
				}
			}
		},
		naviback() {
			uni.navigateBack();
		},
		// 父组件的 methods 中
		handlePressItem(item) {
			if (this.isAction) {
				this.isAction = false;
				this.currentPressItem = {}; // 清空选中项
				this.friendUserId = ''; // 清空关联ID
				this.groupId = '';
				return;
			} else {
				this.isAction = true;
			}

			// 2. 根据类型处理不同逻辑（移除重复的赋值）
			switch (item.type) {
				case 'person':
					console.log('长按人员项：', item);
					// 切换选中/取消选中
					if (this.friendUserId === item.data.friendUserId) {
						this.friendUserId = '';
						this.currentPressItem = {};
					} else {
						this.friendUserId = item.data.friendUserId;
						this.currentPressItem = item; // 存储选中项（用新变量名）
						console.log('选中人员ID：', this.friendUserId);
					}
					break;

				case 'favorite':
					// 收藏项逻辑（补充业务代码）
					this.currentPressItem = item;
					break;

				case 'group':
					// 切换群组选中/取消选中
					if (this.groupId === item.data.groupId) {
						this.groupId = '';
						this.currentPressItem = {};
					} else {
						this.groupId = item.data.groupId;
						this.currentPressItem = item; // 存储选中   项
					}
					break;

				default:
					// 默认情况清空状态
					this.currentPressItem = {};
					this.friendUserId = '';
					this.groupId = '';
					break;
			}
		},
		async getGroups() {
			try {
				const res = await group.getGroup(this.storeData.user.userId);
				console.log('群组', res);
				if (res.code === 0) {
					this.groups = res.data;
				}
			} catch (e) {
				console.error(e);
			}
		},
		async loadContacts() {
			this.currentPage = 1;
			this.isLoading = true;
			try {
				const parma = {
					userId: this.storeData.user.userId,
					keyword: this.keyword,
					page: this.currentPage,
					pageSize: this.pageSize
				};

				const { success, data } = await friend.getFriendList(parma);

				if (!success || !data.length) {
					this.contact = [];
					uni.showToast({
						title: '暂无好友',
						position: 'center'
					});
					this.isLoading = false;
					return;
				}

				this.contact = data || [];
				console.log('取到的好友清单', this.contact);
			} catch (e) {
				console.error('加载通讯录失败：', e);
				uni.showToast({ title: '加载失败', icon: 'none' });
			} finally {
				this.isLoading = false;
			}
		},
		async loadMoreContacts() {
			if (this.isLoading) return;
			this.isLoading = true;
			try {
				const nextPage = this.currentPage + 1;
				const parma = {
					userId: this.storeData.user.userId,
					keyword: this.keyword,
					page: nextPage,
					pageSize: this.pageSize
				};

				const { success, data } = await friend.getFriendList(parma);
				if (success && data.length) {
					this.contact = [...this.contact, ...data];
					this.currentPage = nextPage;
				} else {
					uni.showToast({ title: '已加载全部', icon: 'none' });
				}
			} catch (e) {
				console.error('加载更多联系人失败：', e);
			} finally {
				this.isLoading = false;
			}
		},
		toFavoriteChat(favorite) {
				this.isAction=false
						this.currentPressItem = null; // 清空选中项
						this.friendUserId = ''; // 清空关联ID
						this.groupId = '';
			try {
				const queryParam = {};
				queryParam.id = favorite.favorite_id;
				queryParam.location = favorite.location;
				queryParam.type = favorite.type;
				this.$store.commit('msg/SET_queryParam', queryParam);
				this.$store.commit('msg/SET_isFly', true);
				if (!favorite.location || Object.keys(favorite.location).length === 0) {
					console.error('无定位坐标');
					return;
				}
				setToTarget('favorite', { favorite_id: favorite.favorite_id, favorite_name: favorite.name, location: favorite.location });
				this.$store.commit('msg/SET_location', favorite.location);
				uni.navigateTo({
					url: '/pages/main/main'
				});
			} catch (e) {
				console.warn(e);
			}
		},
		handleGroups(friends) {
			const groupMap = {};
			friends.forEach((friend) => {
				const groupId = friend.groupId || 'default';
				if (!groupMap[groupId]) {
					groupMap[groupId] = {
						groupId,
						groupName: groupId === 'default' ? '未分组' : '',
						members: []
					};
				}
				groupMap[groupId].members.push(friend);
			});
			this.groups = Object.values(groupMap);
		},
		/**
		 * 联系人多选处理方法
		 * @param {Object} person - 选中的联系人对象
		 * @param {number} index - 选中项在列表中的索引
		 */
		select(person, index) {
			// 1. 数据有效性校验
			if (!person || !person.friendDetail || !person.friendDetail.userId) {
				uni.showToast({ title: '联系人信息无效', icon: 'none' });
				return;
			}

			// 2. 群聊邀请场景（多选逻辑）
			if (this.type === 'applyGroup') {
				this.handleGroupInviteMulti(person, index);
				return;
			}

			// 3. 普通聊天场景（仍为单选，直接跳转）
			this.handleNormalChat(person);
		},

		/**
		 * 处理群聊邀请的多选逻辑
		 * @param {Object} person - 选中的联系人对象
		 * @param {number} index - 选中项在列表中的索引
		 */
		handleGroupInviteMulti(person, index) {
			const targetUserId = person.friendDetail.userId;

			// 2.1 取消选择（已选中则移除）
			if (this.selectedIndexes.includes(index)) {
				// 移除索引
				this.selectedIndexes = this.selectedIndexes.filter((idx) => idx !== index);
				// 移除对应的联系人对象
				this.selcList = this.selcList.filter((item) => item.friendDetail.userId !== targetUserId);
				return;
			}

			// 2.2 限制最大选择人数（可选，根据业务需求调整）
			const maxSelectCount = 20; // 假设最多选择20人
			if (this.selectedIndexes.length >= maxSelectCount) {
				uni.showToast({ title: `最多选择${maxSelectCount}人`, icon: 'none' });
				return;
			}

			// 2.3 添加选择
			this.selectedIndexes.push(index); // 记录索引
			this.selcList.push(person); // 记录联系人对象
		},

		/**
		 * 处理普通聊天场景（单选，直接跳转）
		 * @param {Object} person - 选中的联系人对象
		 */
		handleNormalChat(person) {
				this.isAction=false
						this.currentPressItem = null; // 清空选中项
						this.friendUserId = ''; // 清空关联ID
						this.groupId = '';
			const friendDetail = person.friendDetail;
			// 构建聊天参数并跳转（逻辑同之前）
			const queryParam = { id: friendDetail.userId, type: 'person' };
			setToTarget('person', {
				targetId: friendDetail.userId,
				nicName: person.remarkName || friendDetail.nicName || '未知联系人',
				nicPic: friendDetail.nicPic?.url || ''
			});
			this.$store.commit('msg/SET_queryParam', queryParam);
			uni.navigateTo({ url: '/pages/messages/messages' });
		},

		/**
		 * 提交邀请（适配多选，获取所有选中的clientIds）
		 */
		async personadd() {
			if (this.type === 'applyGroup') {
				try {
					if (this.selcList.length === 0) {
						uni.showToast({ title: '请选择至少一位好友', icon: 'none' });
						return;
					}

					// 获取所有选中的用户ID（多选核心：从selcList中提取）
					const clientIds = this.selcList.map((item) => item.friendDetail.userId);
					const userId = this.storeData.user.userId;

					// 调用群聊邀请接口（支持多用户ID）
					const res = await group.inviteUser(userId, { groupId: this.groupId, clientIds });

					if (res.code === 0) {
						uni.showToast({ title: res.message, icon: 'success' });
						// 邀请成功后重置选择状态
						this.selectedIndexes = [];
						this.selcList = [];
						setTimeout(() => uni.navigateBack(), 1500);
					} else {
						uni.showToast({ title: res.message || '邀请失败', icon: 'none' });
					}
				} catch (e) {
					console.error('邀请好友失败：', e);
					uni.showToast({ title: '网络异常，请稍后再试', icon: 'none' });
				}
			}
		},

		handleBtn() {
			switch (this.actionType) {
				case 'person':
					this.$refs.popup.open();
					break;
				case 'group':
					uni.navigateTo({
						url: '/pages/creadGroup/creadGroup'
					});
					break;
				case 'favorite':
					uni.navigateTo({
						url: '/pages/main/main'
					});
					break;
				default:
					return;
			}
		},

		action(type) {
			this.keyword = '';
			this.searchMode = false;
			this.actionType = type;
			this.isAction=false
			this.currentPressItem = null; // 清空选中项
			this.friendUserId = ''; // 清空关联ID
			this.groupId = '';
		},
		toGroupChat(group) {
			this.isAction=false
					this.currentPressItem = null; // 清空选中项
					this.friendUserId = ''; // 清空关联ID
					this.groupId = '';

			setToTarget('group', { groupId: group.groupId, groupName: group.groupName });

			const queryParam = {
				type: 'group',
				id: group.groupId
			};
			this.$store.commit('msg/SET_queryParam', queryParam);
			uni.navigateTo({
				url: '/pages/messages/messages'
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.navi-bar {
	position: fixed;
	left: 0;
	top: 0;
	right: 0;
	z-index: 200;
	background-color: #438acc;
	height: 150rpx;
	width: 100vw;
	display: flex;
	padding-top: 90rpx;
	padding-left: 25rpx;
	padding-right: 25rpx;
	color: #fff;
	font-size: 32rpx;
	font-weight: 600;
	.navi-left {
		height: 60rpx;
	}
	.navi-info {
		flex: 1;
		height: 60rpx;
		margin-left: 25rpx;
	}
	.navi-search {
		flex: 1;
		height: 60rpx;
		margin-left: 25rpx;
		&.search {
			padding: 0 10rpx;
			border-bottom: 1rpx solid #666;
			&::placeholder {
				color: #fff !important;
				opacity: 0.8;
			}
		}
	}
	.navi-right {
		display: flex;
		height: 60rpx;
		gap: 50rpx;
		margin-right: 50rpx;
		margin-left: auto;
	}
}

.action {
	position: fixed;
	left: 0;
	top: 150rpx;
	right: 0;
	display: flex;
	flex-wrap: nowrap;
	gap: 12rpx;
	padding: 16rpx;
	z-index: 999;
	background-color: #fafafa;
	touch-action: none; /* 关键：禁止原生触摸行为 */
	.action-bar {
		width: 33%;
		position: relative;
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 1rpx;
		padding: 10rpx 25rpx;
		font: 28rpx;
		color: #666;
		:active::after {
			content: '';
			position: absolute;
			bottom: 0;
			left: 10%; // 80%宽度居中 = (100%-80%)/2
			width: 80%;
			height: 4rpx;
			background-color: rgba(85, 170, 255, 0.5);
		}
		&.current::after {
			content: '';
			position: absolute;
			bottom: 0;
			left: 10%; // 左右各留10%空白，实现居中
			width: 80%; // 下划线长度80%
			height: 8rpx; // 下划线厚度
			background-color: #55aaff; // 醒目红色
			border-radius: 4rpx; // 可选：圆角更美观
		}
	}
}

/* 新增滚动容器样式 */
.scroll-container {
	width: 100%;
	min-height: calc(100vh - var(--selc-list-height));
	overflow-y: auto;
	-webkit-overflow-scrolling: touch;
	background-color: #fff;
}

/* 优化固定列表样式 */
.selc-list {
	position: fixed;
	left: 0;
	top: 150rpx;
	right: 0;
	display: flex;
	flex-wrap: wrap;
	gap: 12rpx;
	padding: 16rpx;
	z-index: 999;
	background-color: #fafafa;
	border-bottom: 2rpx solid rgba(0, 0, 0, 0.1);
	touch-action: none; /* 关键：禁止原生触摸行为 */
}

/* 列表项：固定高度+宽度，纵向居中，布局整齐 */
.selc-item {
	flex: 0 0 16%; /* 占比 16%，NVUE 兼容，替代 calc */
	display: flex;
	flex-direction: column;
	align-items: center; /* 子元素水平居中 */
	justify-content: center; /* 子元素垂直居中 */
	padding: 12rpx 8rpx; /* 内边距：上下12rpx，左右8rpx */
	height: 120rpx; /* 固定高度，确保所有项一致 */
	border-radius: 8rpx; /* 可选：增加圆角，更美观 */
}

/* 头像容器：固定大小，避免头像变形 */
.avatar-box {
	width: 80rpx; /* 固定宽度 */
	height: 80rpx; /* 固定高度，与头像一致 */
	overflow: hidden; /* 隐藏超出部分，避免头像溢出 */
	border-radius: 8rpx; /* 可选：头像圆角 */
}

/* 头像样式：占满容器，保持比例 */
.avatar {
	width: 100%;
	height: 100%;
}

/* 文字样式：与头像间距 5rpx，优化可读性 */
.item-text {
	font-size: 22rpx;
	color: #b6b6b6; /* 文字白色，与蓝色背景对比 */
	margin-top: 5rpx; /* 核心：头像与文字间距 5rpx */
	white-space: nowrap; /* 不换行 */
	overflow: hidden; /* 超出隐藏 */
	text-overflow: ellipsis; /* 超出显示省略号 */
	max-width: 100%; /* 限制文字宽度，避免溢出 */
	text-align: center; /* 文字居中 */
}

/* 其余原有样式不变... */
.favorite,
.group,
.person {
	padding: 10rpx 20rpx;
}
.selc-person {
	background-color: #e8f0fe;
}
.group-title {
	display: block;
	font-size: 28rpx;
	color: #999;
	margin: 15rpx 0;
	padding-left: 10rpx;
	border-left: 4rpx solid #007aff;
}
.loading,
.empty {
	text-align: center;
	padding: 50rpx 0;
	color: #999;
}
.title {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 10rpx 35rpx;
	font-weight: 600;
	width: 92%;
	height: 60rpx;
	background-color: #e6e6e6;
}
.selected {
	border: 1rpx solid #007aff;
}
.btn {
	position: fixed;
	right: 30rpx;
	bottom: 80rpx;
	z-index: 150;
	height: 100rpx;
	width: 100rpx;
	border-radius: 50rpx;
	background-color: #007aff;
	display: flex;
	align-items: center;
	justify-content: center;
	color: #fff;

	transition: transform 0.3s ease-out, opacity 0.3s ease-out;
	opacity: 1;
}
.btn-hidden {
	transform: translateY(200rpx);
	opacity: 0;
}
</style>
